import { graphql } from "../graphql";
import type { CursorPage } from "../types";
import type { ArticleCreateFn, ArticleGetFn, ArticlesGetFn, ArticleUpdateFn, ArticleView } from "./article.types";

export const articleCreate: ArticleCreateFn = async (input) => {
  const query = `
    mutation ArticleCreate($input: ArticleCreateInput!) {
      articleCreate(input: $input)
    }
  `;
  const result = await graphql(query, { input });
  return result.articleCreate as string;
};

export const articleUpdate: ArticleUpdateFn = async (uid, input) => {
  const query = `
    mutation ArticleUpdate($uid: String!, $input: ArticleUpdateInput!) {
      articleUpdate(uid: $uid, input: $input)
    }
  `;
  const result = await graphql(query, { uid, input });
  return result.articleUpdate as string;
};

// 获取单篇文章
export const articleGet: ArticleGetFn = async (uid) => {
  const query = `
    query ArticleGet($uid: String!) {
      article(uid: $uid) {
        uid
        title
        content
        createdAt
        author {
          nickname
        }
      }
    }
  `;
  const result = await graphql(query, { uid });
  return result.article as ArticleView;
};

export const articlesGet: ArticlesGetFn = async (input) => {
  const query = `
    query ArticlesGet($input: ArticlesGetInput!) {
      articles(input: $input) {
        items {
          uid
          title
          content
          createdAt
          author {
            nickname
          }
        }
        nextCursor
        hasMore
      }
    }
  `;
  const result = await graphql(query, { input });
  return result.articles as CursorPage<ArticleView, string>;
};
